//
//  UIViewController+NavigationBar.swift
//  Pods
//
//  Created by hansir on 2020/5/20.
//

import UIKit
//import RxSwift
//import RxCocoa

// MARK: - 导航条外观设置

public extension UIViewController {
    
    var navigationBarColor: UIColor? {
        
        get { return self.navigationController?.navigationBar.barTintColor }
        
        set {
            if #available(iOS 13.0, *) {
                let appearance = navBar?.standardAppearance ?? UINavigationBarAppearance()
                // 设置导航栏背景色
                appearance.backgroundColor = newValue
                // 带scroll滑动的页面
                navigationController?.navigationBar.scrollEdgeAppearance = appearance
                // 常规页面
                navigationController?.navigationBar.standardAppearance = appearance
            }else{
                self.navigationController?.navigationBar.barTintColor = newValue
            }  
        }
    }
    
    var titleTextAttributes: [NSAttributedString.Key : Any]? {
        
        get { return self.navigationController?.navigationBar.titleTextAttributes }
        
        set { self.navigationController?.navigationBar.titleTextAttributes = newValue }
    }
    
}

// MARK: - 导航条主题

public struct NavBarTheme {
    /// 背景色
    public static let bgColor: UIColor = .white
    /// 底部分割线颜色
    public static let botomLineColor: UIColor = UIColor.gray4
    /// title attrs
    public static let titleAttrs: [NSAttributedString.Key: Any] = [
        .foregroundColor: UIColor.gray11,
        .font: UIFont.systemFont(ofSize: 18, weight: .medium),
        .kern: 0
    ]
    /// left bar button item attrs
    public static let leftBarBtnItemAttrs: [NSAttributedString.Key: Any] = [
        .foregroundColor: UIColor.darkText,
        .font: UIFont.standardFont(size: 16, weight: .regular),
        .kern: 1
    ]
    /// right bar button item attrs
    public static let rightBarBtnItemAttrs: [NSAttributedString.Key: Any] = [
        .foregroundColor: UIColor.darkText,
        .font: UIFont.standardFont(size: 16, weight: .regular),
        .kern: 1
    ]
}

// MARK: - 导航栏相关

public extension UIViewController {
    
    private struct AssociatedKey {
        static var isStatusBarHiddenKey: Int = 0
        static var statusBarStyleKey: Int = 0
        static var navigationBarBgColorKey: Int = 0
        static var titleColorKey: Int = 0
        static var rightBarBtnItemTextColorKey: Int = 0
        static var leftBarBtnItemTextColorKey: Int = 0
        static var isNavigationBarBottomLineHiddenKey: Int = 0
    }
    
    var navigationBarBottomLineImage: UIImage? {
        return UIImage.image(color: NavBarTheme.botomLineColor,
                             size: CGSize(width: ScreenMinSize, height: 0.5))
    }
    
    /// 设置状态栏颜色（处理 iOS 13.0 之后，default 状态和之前版本不同问题）
    func setStatusBar(_ style: UIStatusBarStyle = .default, animated: Bool = false) {
        if style == .default, #available(iOS 13.0, *) {
            UIApplication.shared.setStatusBarStyle(.darkContent, animated: animated)
        } else {
            UIApplication.shared.setStatusBarStyle(style, animated: animated)
        }
    }
    
    var navBar: UINavigationBar? {
        return navigationController?.navigationBar
    }
    
    /// 是否隐藏状态栏 （rn 去掉后修改实现
    var isStatusBarHidden: Bool {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.isStatusBarHiddenKey) as? Bool ?? false
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.isStatusBarHiddenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            UIApplication.shared.isStatusBarHidden = newValue
        }
    }
    
    /// 改变 status bar style
    var statusBarStyle: UIStatusBarStyle {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.statusBarStyleKey) as? UIStatusBarStyle ?? .default
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.statusBarStyleKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            setStatusBar(newValue)
        }
    }
    
    /// 是否隐藏导航栏分割线
    var isNavigationBarBottomLineHidden: Bool {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.isNavigationBarBottomLineHiddenKey) as? Bool ?? false
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.isNavigationBarBottomLineHiddenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            navBar?.shadowImage = newValue ? UIImage() : navigationBarBottomLineImage
        }
    }
    
    /// 改变导航栏颜色和title颜色
    var navigationBarBgColor: UIColor {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.navigationBarBgColorKey) as? UIColor ?? NavBarTheme.bgColor
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.navigationBarBgColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            
            
            if #available(iOS 13.0, *) {
                let appearance = navBar?.standardAppearance ?? UINavigationBarAppearance()
                // 设置导航栏背景色
                appearance.backgroundColor = newValue
                // 带scroll滑动的页面
                navigationController?.navigationBar.scrollEdgeAppearance = appearance
                // 常规页面
                navigationController?.navigationBar.standardAppearance = appearance
            }else{
                navBar?.barTintColor = newValue
            }
        }
    }
    
    /// title color
    var titleColor: UIColor {
        get {
            let defaultColor = NavBarTheme.titleAttrs[.foregroundColor] as! UIColor
            return objc_getAssociatedObject(self, &AssociatedKey.titleColorKey) as? UIColor ?? defaultColor
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.titleColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            if #available(iOS 13.0, *) {
                let appearance = navBar?.standardAppearance ?? UINavigationBarAppearance()
                appearance.titleTextAttributes = [.foregroundColor: newValue]
                // 带scroll滑动的页面
                navigationController?.navigationBar.scrollEdgeAppearance = appearance
                // 常规页面
                navigationController?.navigationBar.standardAppearance = appearance
            }else{
                var titleAttr = navBar?.titleTextAttributes
                titleAttr?[.foregroundColor] = newValue
                navBar?.titleTextAttributes = titleAttr
            }
        }
    }
    
    /// 导航栏 right barbuttonitem text color
    var rightBarBtnItemTextColor: UIColor {
        get {
            let defaultColor = NavBarTheme.rightBarBtnItemAttrs[.foregroundColor] as! UIColor
            return objc_getAssociatedObject(self, &AssociatedKey.rightBarBtnItemTextColorKey) as? UIColor ?? defaultColor
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.rightBarBtnItemTextColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            var attr = navigationItem.rightBarButtonItem?.titleTextAttributes(for: .normal)
            if attr == nil {
                attr = [:]
            }
            attr?[.foregroundColor] = newValue
            navigationItem.rightBarButtonItem?.setTitleTextAttributes(attr, for: .normal)
        }
    }
    
    /// 导航栏 left barbuttonitem text color
    var leftBarBtnItemTextColor: UIColor {
        get {
            let defaultColor = NavBarTheme.leftBarBtnItemAttrs[.foregroundColor] as! UIColor
            return objc_getAssociatedObject(self, &AssociatedKey.leftBarBtnItemTextColorKey) as? UIColor ?? defaultColor
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.leftBarBtnItemTextColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            var attr = navigationItem.leftBarButtonItem?.titleTextAttributes(for: .normal)
            if attr == nil {
                attr = [:]
            }
            attr?[.foregroundColor] = newValue
            navigationItem.leftBarButtonItem?.setTitleTextAttributes(attr, for: .normal)
        }
    }
    
}


// MARK: - 添加 左右 导航按钮

public extension UIViewController {

//    func addLeftBarButton(image: UIImage?, disposeBag: DisposeBag, then: (() -> ())?) {
//        guard let image = image?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal) else { return }
//
//        let item = UIBarButtonItem(image: image,
//                                   style: UIBarButtonItem.Style.plain,
//                                   target: nil,
//                                   action: nil)
//        item.rx.tap.subscribe(onNext: { _ in then?() }).disposed(by: disposeBag)
//        navigationItem.leftBarButtonItem = item
//    }
//
//    func addLeftBarButton(title: String, disposeBag: DisposeBag, then: (() -> ())?) {
//        let item = UIBarButtonItem(title: title,
//                                   style: .plain,
//                                   target: nil,
//                                   action: nil)
//        item.rx.tap.subscribe(onNext: { _ in then?() }).disposed(by: disposeBag)
//        navigationItem.leftBarButtonItem = item
//    }
//
//    func addLeftBarButton(customView: UIView, disposeBag: DisposeBag, then: (() -> ())?) {
//        let item = UIBarButtonItem(customView: customView)
//        let _ = item.rx.tap.subscribe(onNext: { _ in then?() }).disposed(by: disposeBag)
//        navigationItem.leftBarButtonItem = item
//    }
//
//    func addRightBarButton(image: UIImage?, disposeBag: DisposeBag, then: (() -> ())?) {
//        guard let image = image?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal) else { return }
//
//        let item = UIBarButtonItem(image: image,
//                                   style: UIBarButtonItem.Style.plain,
//                                   target: nil,
//                                   action: nil)
//        item.rx.tap.subscribe(onNext: { _ in then?() }).disposed(by: disposeBag)
//        navigationItem.rightBarButtonItem = item
//    }
//
//    func addRightBarButton(title: String, disposeBag: DisposeBag, then: (() -> ())?) {
//        let item = UIBarButtonItem(title: title,
//                                   style: .plain,
//                                   target: nil,
//                                   action: nil)
//        item.rx.tap.subscribe(onNext: { _ in then?() }).disposed(by: disposeBag)
//        navigationItem.rightBarButtonItem = item
//    }
//
//    func addRightBarButton(customView: UIView, disposeBag: DisposeBag, then: (() -> ())? = nil) {
//        let item = UIBarButtonItem(customView: customView)
//        let _ = item.rx.tap.subscribe(onNext: { _ in then?() }).disposed(by: disposeBag)
//        navigationItem.rightBarButtonItem = item
//    }
    
}

// MARK: - 跳转相关

public extension UINavigationController {
    
    /// push 下个页面，并关闭上个页面
    func push(_ viewController: UIViewController,
              animated: Bool = true,
              precondition: @escaping ([UIViewController]) -> [UIViewController]) {
        self.setViewControllers(precondition(viewControllers), animated: animated)
    }
    
    func push(_ viewController: UIViewController,
              animated: Bool = true,
              back skip: Int) {
        push(viewController,
             animated: animated,
             precondition: {
                guard $0.count > 0, skip < $0.count else { return $0 }
                return $0[0..<($0.count - skip)] + [viewController]
        })
    }
    
    /// push 下个页面，并关闭上个页面
    func pushVCPopPreviousVC(_ viewController: UIViewController, animated: Bool = true) {
        var vcs = viewControllers
        guard vcs.count > 0 else { return }
        let range = (vcs.endIndex - 1) ..< vcs.endIndex
        vcs.replaceSubrange(range, with: [viewController])
        setViewControllers(vcs, animated: animated)
    }
}
